<?php

namespace app\pxs\controller;
use app\admin\model\AllocRule;
use app\admin\model\Card;
use app\admin\model\Chat;
use app\admin\model\ClassQu;
use app\admin\model\PushStore as PushStoreModel;
use app\admin\model\PushStoreRule;
use app\admin\model\Qu;
use app\admin\model\RobotSet;
use app\admin\model\Staff;
use app\admin\model\Store;
use  \app\admin\model\UserList;
use app\admin\model\UserPvLog;
use \app\common\Common;
use app\pxs\service\JwtService;
use app\sys\model\UrlSourceLog;
use app\sys\service\GateCli;
use think\facade\Env;
use think\facade\Log;
use think\facade\Validate;
use think\Request;

class User extends Common
{
    // 获取token
    public function getToken(Request $request)
    {
        $agent = $request->header("user-agent");
        $ip = $request->ip();
        $mobile = $request->param("mobile","");
        $beUrl = $request->param("be_url","");
        $afUrl = $request->param("af_url","");

        $data["mobile"] = '';

        if(!isPhone($mobile)){
            $data["mobile"] = decrypt($mobile,Env::get("MOBILE.KEY"));
            $resM = mobiles($data["mobile"]);
            if ($resM){
                return failedJson($resM);
            }
        }else{
            $data["mobile"] = $mobile;
        }

        $token = JwtService::getToken($ip,$agent,$data["mobile"],$beUrl,$afUrl);
        return pxsSuccessJson("success",$token);
    }


    // 添加店铺信息
    public function addStoreCry(Request $request){
        $data = $request->param();
        $validate = Validate::make([
            "id|店铺id" => "require",
            "url|路径" => "require",
            "title|标题" => "length:2,255",
            "img|图片" => "require",
            "address|地址" => "require",
            "industry|行业" => "require",
            "cost|费用" => "require",
            "pv|浏览量" => "require",
            "rent|租金" => "require"
        ]);
        if (!$validate->check($data)) {
            return failedJson($validate->getError());
        }
        $res = Store::addSto($data);
        if (!$res){
            return failedJson($validate->getError());
        }
        unset($data["_user"]);
        return successJson("success",$data);
    }

    // 添加浏览记录
    public function addUserLogCry(Request $request){
        $data = $request->param();
        $validate = Validate::make([
//            "id|店铺id" => "require",
            "url|路径" => "require",
//            "title|标题" => "length:2,255",
//            "img|图片" => "require",
//            "address|地址" => "require",
//            "cost|费用" => "require",
//            "pv|浏览量" => "require",
//            "rent|租金" => "require",

        ]);
        if (!$validate->check($data)) {
            return failedJson($validate->getError());
        }
//        print_r($data);exit();
        $jwt = $request->_user;
        $data["user_no"] = $jwt["no"];
//        $data["user_icon"] = $request->param("user_icon");
//        $data["industry"] = $request->param("industry");

//        $mobile = $request->param("mobile","");
//        $data["mobile"] = decrypt($mobile,Env::get("MOBILE.KEY"));
//        $resM = mobiles($data["mobile"]);
//        if ($resM){
//            return failedJson($resM);
//        }
//
        list($err,$dataUrl) = GetGwUrlInfo($data["url"]);
        if($err == "false"){
            return failedJson( $dataUrl);
        }

        $shopPhone = $dataUrl["shop_phone"];
        $dataUrl["shop_phone"] = decrypt($shopPhone,Env::get("MOBILE.KEY"));

        $res = UserPvLog::addLog($dataUrl);
        if (!$res){
            return failedJson($validate->getError());
        }
        unset($data["_user"]);
        return successJson("success",$dataUrl);
    }

    // 发送消息给客服
    public function sendInfoToStaffCry(Request $request){
        $data = $request->param();
        $validate = Validate::make([
            "to_staff_no|客服编号" => "require",
            "store_id|店铺id" => "number",

        ]);
        if (!$validate->check($data)) {
            return failedJson($validate->getError());
        }
        $data["chat_info"] = $request->param("chat_info","");
        $data["store_id"] = $request->param("store_id",0);

        $url = $request->param("url","");

        // 电话解密
        $data["mobile"] = "";
        $mobile = $request->param("mobile","");
        if($mobile){
            $data["mobile"] = decrypt($mobile,Env::get("MOBILE.KEY"));
            $resM = mobiles($data["mobile"]);
            if ($resM){
                return failedJson($resM);
            }
        }else{
            // 兼顾app端
            if (isset($jwt["mobile"]))
            {
                $data["mobile"] = $jwt["mobile"];
            }
        }

        $jwt = $request->_user;
        $data["user_no"] = $jwt["no"];

        if(isset($data["mobile"]) && !empty($data["mobile"]) && $jwt["mobile"] != $data["mobile"])  {
            return failedJson("会员不匹配~");
        }

        $staffInfo = \app\admin\model\Staff::where("staff_no",$data["to_staff_no"])->find();
        if (!$staffInfo){
            return failedJson("该客服不存在~");
        }

        $data["duty_id"]= $staffInfo["duty_id"];
        $data["server_type"]= serverType($staffInfo["duty_id"]);

        $ip = $request->ip();
        $res = UserList::toStaff($ip,$data,$staffInfo,$jwt["device_id"],$url);
        if($res){
            return failedJson($res);
        }
        return successJson("success","发送成功");
    }

    // 获取聊天消息
    public function getInfoCry(Request $request){
        $data = $request->param();
        $validate = Validate::make([
            "staff_no|客服编号" => "require",
        ]);
        if (!$validate->check($data)) {
            return failedJson($validate->getError());
        }
        $chatId = $request->param("chat_id","0");
        $chatLogId = $request->param("chat_log_id","0");
        $page = $request->param("page","0");
        $limit = $request->param("limit","10");

        // 电话解密
//        $mobile = $request->param("mobile","");
//        $data["mobile"] = decrypt($mobile,Env::get("MOBILE.KEY"));
//        $resM = mobiles($data["mobile"]);
//        if ($resM){
//            return failedJson($resM);
//        }

        // 电话解密
        $data["mobile"] = "";
        $mobile = $request->param("mobile","");
        if($mobile){
            $data["mobile"] = decrypt($mobile,Env::get("MOBILE.KEY"));
            $resM = mobiles($data["mobile"]);
            if ($resM){
                return failedJson($resM);
            }
        }else{
            // 兼顾app端
            if (isset($jwt["mobile"]))
            {
                $data["mobile"] = $jwt["mobile"];
            }
        }

        $jwt = $request->_user;
        $data["user_no"] = $jwt["no"];
        if(!empty($mobile) && $jwt["mobile"] != $data["mobile"])  {
            return failedJson("会员不匹配~");
        }
        list($userDate,$err) = \app\admin\model\User::getIsUserMember($data["user_no"],$data["mobile"]);
        if($err){
            return failedJson($err);
        }

        $staffInfo = Staff::where("staff_no",$data["staff_no"])->find();
        if(!$staffInfo){
            return failedJson("客服不在线~");
        }
        $list = UserList::getInfo($staffInfo["id"],$userDate["id"],$chatId,$chatLogId,$page,$limit);
        return successJson("success",$list);
    }

    // 修改消息状态（未读）
    public function upInfoStatusCry(Request $request){
        $data = $request->param();
        $validate = Validate::make([
            "staff_no|客服编号" => "require",
//            "chat_id|聊天id" => "require",
        ]);
        if (!$validate->check($data)) {
            return failedJson($validate->getError());
        }
        $jwt = $request->_user;
        $data["user_no"] = $jwt["no"];
        // 电话解密
//        $mobile = $request->param("mobile","");
//        $data["mobile"] = decrypt($mobile,Env::get("MOBILE.KEY"));
//        $resM = mobiles($data["mobile"]);
//        if ($resM){
//            return failedJson($resM);
//        }

        // 电话解密
        $data["mobile"] = "";
        $mobile = $request->param("mobile","");
        if($mobile){
            $data["mobile"] = decrypt($mobile,Env::get("MOBILE.KEY"));
            $resM = mobiles($data["mobile"]);
            if ($resM){
                return failedJson($resM);
            }
        }else{
            // 兼顾app端
            if (isset($jwt["mobile"]))
            {
                $data["mobile"] = $jwt["mobile"];
            }
        }

        $staffInfo = Staff::where("staff_no",$data["staff_no"])->find();
        if(!$staffInfo){
            return failedJson("客服不在线~");
        }
        list($userInfo,$err) = \app\admin\model\User::getIsUserMember($data["user_no"],$data["mobile"]);
        if($err){
            return failedJson($err);
        }

        $res = UserList::upStatus($data["chat_id"],$userInfo["id"],$staffInfo["id"],"user");
        if ($res){
            return failedJson($res);
        }
        // 发送信息
        $isMen = 0;
        if($userInfo["mobile"])$isMen = 1;
        $gate  = new GateCli();
        $gate->userUpNew($data["staff_no"],$staffInfo["id"],$data["chat_id"],$isMen);
        return successJson("success","修改成功");
    }

    // 获取对接售前客服
    public function getStaffBe(Request $request)
    {
        $url = $request->param("url");
        if (!$url){
            return failedJson("url不能为空~");
        }
        $jwt = $request->_user;
        $data["user_no"] = $jwt["no"];
        $data["url"] = $url;
        $staffNo = AllocRule::allocRule($jwt->no,$url,"be");
        $res = Staff::alias("s")
            ->leftJoin("ic_token t","t.staff_no = s.staff_no")
            ->field("s.staff_no,s.staff_name,s.icon,t.device_type as user_agent")
            ->where("s.staff_no",$staffNo)->find();
        if(!$res)return failedJson("客服不存在~");
        return successJson("success",$res);
    }

    // 客服列表
    public function staffList(Request $request)
    {
        $search = $request->param("search","");
        $page = $request->param("page","0");
        $limit = $request->param("limit","10");

        $jwt = $request->_user;
        // 电话解密
        $data["mobile"] = "";
        $mobile = $request->param("mobile","");
        if($mobile){
            $data["mobile"] = decrypt($mobile,Env::get("MOBILE.KEY"));
            $resM = mobiles($data["mobile"]);
            if ($resM){
                return failedJson($resM);
            }
        }else{
            // 兼顾app端
            if (isset($jwt["mobile"]))
            {
                $data["mobile"] = $jwt["mobile"];
            }
        }

        $list = UserList::getList($data["mobile"],$jwt["no"],$search,$page,$limit);
        return successJson("success",$list);
    }

    // 留言
    public function messageBoard(Request $request)
    {
        $data = $request->param();
        $validate = Validate::make([
            "mobile|电话" => "mobile",
            "store_type|店"=>"number"
        ]);
        if (!$validate->check($data)) {
            return failedJson($validate->getError());
        }
        $jwt = $request->_user;
        $data["user_no"] = $jwt["no"];
        $name = $request->param("name","");
        $staffNo = $request->param("staff_no","");
        $url = $request->param("url","");

        $mp = Card::ifExCard($data["mobile"]);
        if($mp){
            return failedJson("电话已添加");
        }

        $res = \app\admin\model\User::saveInfo($jwt["no"],$data["mobile"],"",$name,"我想",$data["store_type"],"极速通道",$staffNo,$url);
        if($res)return failedJson($res);
        return successJson("success","成功");
    }

    // 获取对接售后客服
    public function getStaffAf(Request $request)
    {
        $staffNo = $request->param("staff_no","");

        $jwt = $request->_user;
        $data["user_no"] = $jwt["no"];

        // 机器人 服役
        if(RobotSet::timeOut()){
            $res = RobotSet::field("s.staff_id,s.staff_no,r.name as staff_name,r.icon,'' as user_agent")->alias("r")
                ->leftJoin("ic_staff s","s.staff_no = 'PXS000000'")
                ->find();
        }else{
            // 判断是否在职
            $staffNo = Staff::where("staff_no",$staffNo)->where("delete_time",0)->where("on_status",1)
                ->value("staff_no","");
            if (!$staffNo){
                $staffNo = AllocRule::allocRule($jwt->no,"","af");
            }
            $res = Staff::alias("s")
                ->leftJoin("ic_token t","t.staff_no = s.staff_no")
                ->field("s.id as staff_id,s.staff_no,s.staff_name,s.icon,t.device_type as user_agent")
                ->where("s.staff_no",$staffNo)->find();
            if($res){
                $res["staff_name"] = getStaffName($res["staff_name"]);
            }else{
                // 无客服可分配
                $userId = \app\admin\model\User::where("no",$data["user_no"])->value("id",0);
                // 对话过才提示
                if($userId){
                    chat::TisToUser($userId, $res["staff_id"], 0, "无客服可分配");
                }
            }
        }

        return successJson("success",$res);
    }

    public function getHotTitle(Request $request)
    {
        $res = PushStoreRule::field("id,title")->select();
        return successJson("success",$res);
    }


    public function getStore(Request $request)
    {
        $staffNo = $request->param("staff_no");
        $ids = $request->param("id",[]);
        $jwt = $request->_user;
        $data["user_no"] = $jwt["no"];
        $data["mobile"] = $jwt["mobile"];
        // 延迟发送
        sleep(1);
        $res = Chat::robotStoreToUser($data["user_no"],$data["mobile"],$staffNo,$ids);
        return successJson("success",$res);
    }

    public function getQuClass(Request $request)
    {
        $q = ClassQu::field("id,title")->select();
        $arr = array();
        foreach ($q as $k => $v){
            $arr[$k] = ["id"=>$v["id"],"title"=>$v["title"],"children"=>[]];
            $s = Qu::field("id,title")->where("qu_id",$v["id"])->select();
            foreach ($s as $ke => $vu){
                $arr[$k]["children"][] = ["id"=>$vu["id"],"title"=>$vu["title"],"children"=>""];
            }
        }
        return successJson("success",$arr);
    }

    public function getQu(Request $request)
    {
        $id = $request->param("id",0);
        $staffNo = $request->param("staff_no");
        $jwt = $request->_user;

        if(!RobotSet::timeOut()){
            // 延迟发送
            sleep(1);
            $ro = Chat::robotQuToUser($jwt["no"],$staffNo,$id);
            if($ro){
                return failedJson($ro);
            }
        }

        return successJson("success","成功~");
    }


    public function getChatNum(Request $request)
    {
        $mobile = $request->param("mobile","");
        $mobileDe= "";

        if($mobile){
            $mobileDe = decrypt($mobile,Env::get("MOBILE.KEY"));
            $resM = mobiles($mobileDe);
            if ($resM){
                return failedJson($resM);
            }
        }
        if(empty($mobileDe)){
            return failedJson("电话不能为空~");
        }
        $da = Chat::unreadChat($mobileDe);
        return successJson("success",$da);
    }

    /***
     * 修改店铺状态
     * @param Request $request
     * @return false|string
     */
    public function upStatus(Request $request)
    {
        $storeId = $request->param("store_id","");
        $storeStatus = $request->param("store_status");
        PushStoreModel::upStatus($storeId,$storeStatus);
        return successJson("success","成功~");
    }

    /**
     * 添加店铺
     * @param Request $request
     * @return false|string
     */
    public function addSto(Request $request)
    {
        $urlArr = $request->param("url",[]);
        $user = $request->_user;
        foreach($urlArr as $key => $url){
            $res = PushStoreModel::add($url,$user["staff_no"],$user["staff_name"]);
            if($res){
                Log::info("addSto失败~".$url.$res);
            }
        }
        return successJson("success","成功~");
    }

}